package com.dangdang.serviceImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.Book;
import com.dangdang.service.BookService;
import com.dangdang.util.HbnUtils;

/**
 * 图书管理类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-17
 */
public class BookServiceImpl implements BookService {

	@Override
	public void addBook(Book book) {
		Session session = HbnUtils.getSession();
		try {
			session.beginTransaction();
			session.save(book);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
	}

	@Override
	public void deleteBook(Book book) {
		Session session = HbnUtils.getSession();
		try {
			session.beginTransaction();
			session.delete(book);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Book> findAllBook() {
		Session session = HbnUtils.getSession();
		Query query = session.createQuery("from Book");
		List<Book> bookList = query.list();
		session.close();
		return bookList;
	}

	@Override
	public Book findBookById(Integer booId) {
		Session session = HbnUtils.getSession();
		Book receiveBook = (Book) session.get(Book.class, booId);
		session.close();
		if (null != receiveBook) {
			return receiveBook;
		}
		return null;
	}

	@Override
	public void updateBook(Book book) {
		Session session = HbnUtils.getSession();
		try {
			session.beginTransaction();
			session.update(book);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
